<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="模块列表"
      row-key="_id"
      :indent="20"
      :columns="columns"
      :request-api="getTableList"
      :pagination="false"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')"> 新增 </el-button>
        <el-button
          type="primary"
          plain
          :icon="CirclePlus"
          :disabled="!scope.isSelected"
          @click="openDrawer('新增下级', {}, scope.selectedList)"
        >
          新增下级
        </el-button>
        <el-button type="primary" :icon="Upload" plain @click="batchAdd">导入数据</el-button>
        <el-button type="primary" :icon="Download" plain @click="downloadFile">导出数据</el-button>
      </template>

      <!-- 模块操作 -->
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)"> 编辑 </el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteData(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
    <ModuleDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="ts" name="moduleManage">
import { ref, computed, onMounted } from "vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { Delete, EditPen, CirclePlus, View, Upload, Download } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import apiService from "@/api/services/apiService";
import ModuleDrawer from "./moduleDrawer.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { dateRender } from "@/hooks/useColumnRender";
import { Module, ExportObj } from "@/api/types/base";
import { useDataStore } from "@/stores/modules/data";
import { ElMessageBox } from "element-plus";
import { useDateFormat } from "@vueuse/core";
import { ExportColType } from "@/enums/sysEnum";

const proTable = ref();
const dataStore = useDataStore();

// 获取产品列表
const productList = computed(() => dataStore.productList);
onMounted(() => {
  dataStore.findProductList();
});

const getTableList = (params: any) => {
  params.options.sort = {
    sort: 1
  };
  return apiService.findTree("module", params.condition, params.options);
};

// 表格配置项
const columns: ColumnProps[] = [
  { type: "index", label: "序号", width: 85 },
  { prop: "name", label: "模块名称", align: "left", width: 200, search: { el: "input", like: true } },
  {
    prop: "productId",
    label: "所属产品",
    enum: productList,
    search: { el: "select", props: { filterable: true } },
    fieldNames: { label: "name", value: "_id" }
  },
  {
    prop: "important",
    label: "重要性",
    enum: () => apiService.findClassify("MODULE_IMPORTANT"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "manage", label: "后台管理", render: ({ row }) => (row.manage ? "√" : "") },
  { prop: "app", label: "App端", render: ({ row }) => (row.app ? "√" : "") },
  { prop: "pc", label: "PC端", render: ({ row }) => (row.pc ? "√" : "") },
  { prop: "web", label: "Web端", render: ({ row }) => (row.web ? "√" : "") },
  { prop: "pad", label: "Pad端", render: ({ row }) => (row.pad ? "√" : "") },
  { prop: "sort", label: "排序" },
  {
    prop: "state",
    label: "状态",
    search: { el: "select", props: { filterable: true } },
    enum: () => apiService.findClassify("DATA_STATE"),
    fieldNames: { label: "name", value: "value" }
  },
  { prop: "createDate", label: "创建时间", width: 120, render: dateRender },
  { prop: "operation", label: "操作", width: 220, fixed: "right" }
];

// 删除模块信息
const deleteData = async (params: Module) => {
  await useHandleData(apiService.deleteById, "module", params._id, `删除模块【${params.name}】`);
  proTable.value?.getTableList();
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof ModuleDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<Module> = {}, selectList: { [key: string]: any }[] = []) => {
  if (title.indexOf("新增") !== -1) {
    selectList?.length ? (row.pid = selectList[0]._id) : delete row.pid;
  }
  const params = {
    title,
    tbName: "module",
    isView: title === "查看",
    row: { ...row },
    api: title.indexOf("新增") !== -1 ? apiService.save : title === "编辑" ? apiService.updateById : undefined,
    getTableList: proTable.value?.getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 导入导出功能
const getExcelConfig = (): ExportObj => {
  return {
    params: proTable.value?.totalParam,
    tableName: "module",
    keyPropName: "name",
    enumTypes: ["MODULE_IMPORTANT", "DATA_STATE"],
    tableConfigs: [],
    header: [
      { header: "序号", width: 6, ext: { prop: "index", type: ExportColType.INDEX } },
      { header: "模块名称", width: 20, ext: { prop: "name", type: ExportColType.DEFAULT } },
      {
        header: "所属产品",
        width: 15,
        ext: { prop: "productId", type: ExportColType.TABLE, key: "product", value: "_id", label: "name" }
      },
      {
        header: "重要性",
        width: 10,
        ext: { prop: "important", type: ExportColType.ENUM, key: "MODULE_IMPORTANT", value: "value", label: "name" }
      },
      { header: "后台管理", width: 10, ext: { prop: "manage", type: ExportColType.DEFAULT } },
      { header: "App端", width: 10, ext: { prop: "app", type: ExportColType.DEFAULT } },
      { header: "PC端", width: 10, ext: { prop: "pc", type: ExportColType.DEFAULT } },
      { header: "Web端", width: 10, ext: { prop: "web", type: ExportColType.DEFAULT } },
      { header: "Pad端", width: 10, ext: { prop: "pad", type: ExportColType.DEFAULT } },
      { header: "排序", width: 10, ext: { prop: "sort", type: ExportColType.DEFAULT } },
      {
        header: "状态",
        width: 10,
        ext: { prop: "state", type: ExportColType.ENUM, key: "DATA_STATE", value: "value", label: "name" }
      },
      { header: "创建时间", width: 15, ext: { prop: "createDate", type: ExportColType.DATE_TIME } }
    ]
  };
};

// 导出数据
const downloadFile = async () => {
  ElMessageBox.confirm("确认导出数据?", "温馨提示", { type: "warning" }).then(() =>
    useDownload(apiService.commonExport, `模块清单-${useDateFormat(new Date(), "YYYY-MM-DD").value}`, "", getExcelConfig(), false)
  );
};

// 导入数据
const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null);
const batchAdd = () => {
  const params = {
    title: "模块",
    defaultTip: "模块名称已有则跳过",
    coverTip: "模块名称相同则覆盖",
    tempUrl: "/template/module",
    getTableList: proTable.value?.getTableList,
    importApi: apiService.commonImport,
    config: getExcelConfig()
  };
  dialogRef.value?.acceptParams(params);
};
</script>
